<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ga extends Base_Controller
{

	private $InitalizationKey;
	private $qr_name;

	protected $rules = array(

		"rule" => array(			
			array(
				'field'   => 'code', 
				'label'   => '验证码', 
				'rules'   => 'trim|required|numeric'
			),
			array(
				'field'   => 'ga', 
				'label'   => '状态', 
				'rules'   => 'trim|required|numeric'
			),
		),
	);

	public function __construct(){
		parent::__construct();
		$this->load->library('Google2FA');
		$this->qr_name = $this->session->userdata('uname').'@boc';
		$this->InitalizationKey = msubstr(base64_encode(passwd($this->session->userdata('mid'))),0,15,'utf8',false);
	}

	public function index($v = false)
	{
		// 生成验证码
		// $TimeStamp	  = $this->google2fa->get_timestamp();
		// $secretkey 	  = $this->google2fa->base32_decode($this->InitalizationKey);
		// $otp       	  = $this->google2fa->oath_hotp($secretkey, $TimeStamp);
		$vdata['title'] = "Google 两步验证";
		$vdata['it'] = $this->mmger->get_one(array('id'=>$this->session->userdata('mid')),"ga");
		$this->load->view('inc_header.php',$vdata);
		$this->load->view('ga_index.php');
		$this->load->view('inc_footer.php');
	}

	public function open()
	{
		$vdata = array('status'=>0,'msg'=>'请提供验证码。');
		$this->form_validation->set_rules($this->rules['rule']);
		if ($this->form_validation->run() == FALSE) {
			$vdata = array( 'status' => 0, 'msg' => validation_errors());
		}else{
			$code = $this->form_validation->set_value('code');			
			$ga  = $this->form_validation->set_value('ga');

			$result = $this->google2fa->verify_key($this->InitalizationKey, $code);
			if ($result) {
				// TODO 开启验证状态
				$vdata = array('status'=>1,'msg'=>'通过验证');
				if ($ga) {
					$ga = 1;
					$vdata['msg'] = "已开启两步验证";
				}else{
					$ga = 0;
					$vdata['msg'] = "已关闭两步验证";
				}
				$this->mmger->update(
					array('ga'=>$ga),
					array('id'=>$this->session->userdata('mid'))
				);
			}else{
				$vdata = array('status'=>0,'msg'=>'请填写正确的验证码!');
			}
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($vdata));
	}

	// 验证 code
	public function verify($code)
	{
		$vdata = array('status'=>0,'msg'=>'请提供验证码。');
		if ($code) {
			$result = $this->google2fa->verify_key($this->InitalizationKey, $code);
			if ($result) {
				$vdata = array('status'=>1,'msg'=>'通过验证');
			}else{
				$vdata = array('status'=>0,'msg'=>'请填写正确的验证码!');
			}
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($vdata));
	}

	// 输出img QR图皮
	public function qr()
	{
		$qr = "http://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/".$this->qr_name."?secret=".$this->InitalizationKey;
		header("Content-Type:image/png");
		echo file_get_contents($qr);
	}
}